/*
 * @Author: NtyAaron
 * @Date: 2021-04-12 11:13:45
 * @LastEditors: NtyAaron
 * @LastEditTime: 2021-06-02 14:14:19
 * @Description: file content
 * @FilePath: \miniapp\dwq\pages\addTaxes\addTaxes.js
 */

import { saveStay } from '../../api/daysOfStay/daysOfStay'
import { getLocationByCoordinate } from '../../api/pubService/pubService.js'
const util = require('../../utils/util.js')
import { _t } from '../../i18n/base'
import { getCity, getDefCity, getLangCityName } from '../../utils/cityJson'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
let year = new Date().getFullYear()
Page({
  data: {
    radio: '1',
    showDialog: false, //弹窗
    cityTxt: getLangCityName('广州'),
    showDatePicker: false,
    currentDate: new Date().getTime(),
    currentDateStr: util.formatDate(new Date()) + ' ' + '00:00',
    minDate: year + '-01-01',
    // maxDate: new Date().getTime(),
    columns: [],
    lang: {},
    stayId: '',
    timeStr: '00:00',
    showTimePicker: false,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      }
      return value
    },
  },
  // 打开城市选择弹窗
  chooseCity() {
    this.setData({
      showDialog: true,
    })
  },
  // 修改城市
  onChangeCity(event) {
    const { picker, value, index } = event.detail
    picker.setColumnValues(1, this.data.cityParse[value[0]])
  },
  // 城市取消按钮
  onCancelCityHandle() {
    this.setData({
      showDialog: false,
    })
  },
  // 确定城市
  onConfirmCity(event) {
    const { picker, value, index } = event.detail
    this.setData({
      cityTxt: value[1],
      showDialog: false,
    })
  },
  // 提示方式选择
  onChange({ detail }) {
    this.setData({
      radio: detail,
    })
    if (detail == 2) {
      Dialog.alert({
        title: this.data.lang['需要关注服务号才能获取通知'],
        message: this.data.lang['点击右上角进入小程序详情页，点击相关官方账号即可关注'],
        confirmButtonText: this.data.lang['确定'],
      }).then(() => {})
    }
  },
  // 确定日期
  confirmDate({ detail }) {
    // if (detail == 'Invalid Date') {
    //   wx.showToast({
    //     title: '请选择日期',
    //   })
    // } else {
    //   this.setData({
    //     currentDateStr: [],
    //     currentDate: detail,
    //     currentDateStr: util.formatDate(new Date(detail)),
    //     showDatePicker: false,
    //     showTimePicker: true,
    //   })
    // }
    this.setData({
      currentDateStr: [],
      currentDate: detail.date,
      currentDateStr: detail.date,
      showDatePicker: false,
      showTimePicker: true,
    })
  },
  // 关闭日期选择弹窗
  showOrHidden() {
    this.setData({
      showDatePicker: !this.data.showDatePicker,
    })
  },
  onCancelCity() {
    this.setData({
      showDialog: false,
    })
  },
  // 开始计算 新增编辑停留日数
  async addTaxesHandle() {
    let userInfo = JSON.parse(wx.getStorageSync('userInfo'))
    let saveStayObj = {
      city: this.data.cityTxt,
      entryTime: this.data.currentDateStr,
      remind: this.data.radio,
      userId: userInfo.userId,
      entryStatus: 1,
    }
    if (this.data.stayId) {
      saveStayObj.stayId = this.data.stayId
      let res = await saveStay(saveStayObj)
      if (res.code == 201 && res.description) {
        Toast(res.description)
      }
      if (res.result) {
        // 此时返回的是最新生成的记录，应当应用渲染到主界面和停留日数主界面
        wx.setStorageSync('entryData', JSON.stringify(res.result))
        this.addBack()
      }
    } else {
      let res = await saveStay(saveStayObj)
      if (res.code == 201 && res.description) {
        Toast(res.description)
      }
      if (res.result) {
        // 此时返回的是最新生成的记录，应当应用渲染到主界面和停留日数主界面
        wx.setStorageSync('entryData', JSON.stringify(res.result))
        this.addBack()
      }
    }
  },
  // 获取当前定位
  async initNowLocation() {
    let locaInfo = await wx.getLocation({
      type: 'wgs84',
      altitude: false,
    })
    let { result } = await getLocationByCoordinate(locaInfo)
    let cityName = result.ad_info.city
    let index = cityName.indexOf('市')
    let city = cityName.substring(0, index)
    this.setData({
      cityTxt: getLangCityName(city),
    })
  },
  // 返回上一级页面
  addBack() {
    wx.navigateBack({
      delta: 1,
    })
  },
  // 跳转详情说明
  toTaxDetailHandle() {
    wx.navigateTo({
      url: '/pages/taxExemptionPolicyDetail/taxExemptionPolicyDetail',
    })
  },
  // 初始化时分
  eggTime() {
    let hours = []
    let mins = []
    for (let i = 0; i <= 23; i++) {
      let hour = i.toString().padStart(2, '0')
      hours.push(hour)
    }
    for (let j = 0; j <= 59; j++) {
      let min = j.toString().padStart(2, '0')
      mins.push(min)
    }
    let columns = [
      {
        values: hours,
        defaultIndex: 0,
      },
      {
        values: mins,
        defaultIndex: 0,
      },
    ]
    this.setData({
      columns: columns,
    })
  },
  // 关闭 时间弹窗
  onTimeCloseHandle() {
    this.setData({
      showTimePicker: false,
    })
  },
  // 确认时分
  onTimeConfirmHandle({ detail }) {
    let val = detail.value
    this.setData({
      timeStr: `${val[0]}:${val[1]}`,
      showTimePicker: false,
    })
    this.setData({
      currentDateStr: this.data.currentDateStr + ' ' + this.data.timeStr,
    })
  },
  // 取消时分
  onTimeCancelHandle() {
    this.setData({
      showTimePicker: false,
    })
  },
  // 跳转重要告示
  toDetailHandle() {
    wx.switchTab({
      url: `/pages/kit/kit`,
    })
  },
  //初始化数据
  initData() {
    const citys = getCity()
    let cityParse = JSON.parse(JSON.stringify(citys))
    delete cityParse['澳门']
    delete cityParse['澳門']
    delete cityParse['香港']
    delete cityParse['台湾']
    delete cityParse['臺灣']
    delete cityParse['Hong Kong']
    delete cityParse['Macao']
    delete cityParse['Taiwan']
    let data = {
      cityParse,
      columnsCity: [
        {
          values: Object.keys(cityParse),
        },
        {
          values: cityParse[getDefCity()],
          defaultIndex: 1,
        },
      ],
    }
    this.setData(data)
  },
  onShow() {
    this.eggTime()
    this.initNowLocation()
  },
  onLoad(e) {
    this.setData({
      lang: _t(),
      language: wx.getStorageSync('language'),
    })
    wx.setNavigationBarTitle({
      title: this.data.lang['新增停留日数提示'],
    })
    if (e.stayId) {
      this.setData({
        stayId: e.stayId,
      })
    }
    this.initData()
  },
})
